﻿using System.Windows;
using System.Windows.Controls;

namespace Pfz.WpfControls
{
	/// <summary>
	/// Represents a header for a HeadedWrapGrid.
	/// </summary>
	public class WrapGridHeader:
		UserControl
	{
		/// <summary>
		/// Creates a new instance.
		/// </summary>
		public WrapGridHeader()
		{
			MaxWidth = double.PositiveInfinity;
			MinWidth = 20;
		}

		internal HeadedWrapGrid _owner;
		/// <summary>
		/// Gets the grid that owns this header.
		/// </summary>
		public HeadedWrapGrid Owner
		{
			get
			{
				return _owner;
			}
		}

		internal int _index;
		/// <summary>
		/// Gets the index of this header.
		/// </summary>
		public int Index
		{
			get
			{
				return _index;
			}
		}

		/// <summary>
		/// Gets or sets the Width of this column.
		/// </summary>
		public GridLength ColumnWidth { get; set; }

		/// <summary>
		/// Resizes the related columns.
		/// </summary>
		protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo)
		{
			base.OnRenderSizeChanged(sizeInfo);

			if (sizeInfo.WidthChanged)
				_Resize();
		}

		internal void _Resize()
		{
			double add;
			if (_index == 0)
				add = _owner.SplitterWidth / 2;
			else
			if (_index == _owner.Headers.Count - 1)
			{
				add = _owner.SplitterWidth / 2;

				add += _owner._grid.ActualWidth - _owner._scrollViewer.ActualWidth;
			}
			else
				add = _owner.SplitterWidth;

			double newWidth = ActualWidth + add;
			_owner._grid.ColumnWidths[_index] = new GridLength(newWidth);
		}
	}
}
